<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Middleware;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use Common\Common;
use Hyperf\Context\Context;
use Mine\Support\Traits\ParserRouterTrait;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;

class CheckJwtTokenMiddleware implements MiddlewareInterface
{ 
    use ParserRouterTrait;
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $jwt = $request->getHeader('Authorization')[0]?? '';
        $jwtData = Common::parseJwt($jwt);
        if (!$jwtData) {
            throw new BusinessException(ResultCode::UNAUTHORIZED);
        }
        if (!$jwtData['id']) {
            throw new BusinessException(ResultCode::UNAUTHORIZED);
        }
        Context::set('jwtData', $jwtData);
        return $handler->handle($request);
    }
}